import { useEffect, useState } from 'react';
import { FetchGoodsList, FetchToCart } from '../../api'
import { debounce, throttle } from 'lodash'

// 所有的操作都定义成函数

const Home = () => {
  const [cart, setCart] = useState<any[]>([])

  useEffect(() => {
    getGoodsList({page:0, size: 5})
  }, [])

  // 请求购物车数据
  const getGoodsList = async ({page, size}: { page: number, size: number}) => {
    const data = await FetchGoodsList({page, size})
    console.log('data:....', data.data)
    setCart(cart => [...data.data])
  }

  const handleToCart = debounce(({skuId}: {skuId: string}) => {
    FetchToCart({skuId}).then(res => {
      console.log('data:...:', res)
    })
  }, 500)

  return <div>
     {
       cart.map(item => {
         return <div key={item.id}>
           id: {item.id} -》 name: {item.imgUrl} -》price: {item.price} -》price: {item.skuCount}
           <button onClick={() => handleToCart({skuId: item.skuId})}>添加</button>
           <br/>
            <hr/>
         </div>
       })
     }
  </div>
}

export default Home;